'''
Created on 2013. 9. 8.

The source is taken from: http://rosettacode.org/wiki/Tree_traversal#Python

Implement a binary tree where each node carries an integer, and implement preoder, inorder, postorder and level-order traversal. Use those traversals to output the following tree: 
         1
        / \
       /   \
      /     \
     2       3
    / \     /
   4   5   6
  /       / \
 7       8   9


The correct output should look like this: 
preorder:    1 2 4 7 5 3 6 8 9
inorder:     7 4 2 5 1 8 6 9 3
postorder:   7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9

'''
from __future__ import print_function
from collections import namedtuple
 
def print_with_space(i):
    print("{0} ".format(i), end="")
 
def preorder(node, visitor = print_with_space):
    if node is not None:
        visitor(node.data)
        preorder(node.left, visitor)
        preorder(node.right, visitor)
 
def inorder(node, visitor = print_with_space):
    if node is not None:
        inorder(node.left, visitor)
        visitor(node.data)
        inorder(node.right, visitor)
 
def postorder(node, visitor = print_with_space):
    if node is not None:
        postorder(node.left, visitor)
        postorder(node.right, visitor)
        visitor(node.data)
 
def levelorder(node, more=None, visitor = print_with_space):
    if node is not None:
        if more is None:
            more = []
        more += [node.left, node.right]
        visitor(node.data)
    if more:    
        levelorder(more[0], more[1:], visitor)
 
if __name__ == '__main__':
    Node = namedtuple('Node', 'data, left, right')
    tree = Node(1,
            Node(2,
                 Node(4,
                      Node(7, None, None),
                      None),
                 Node(5, None, None)),
            Node(3,
                 Node(6,
                      Node(8, None, None),
                      Node(9, None, None)),
                 None))
    print('  preorder: ', end = '')
    preorder(tree)
    print('\n   inorder: ', end = '')
    inorder(tree)
    print('\n postorder: ', end = '')
    postorder(tree)
    print('\nlevelorder: ', end = '')
    levelorder(tree)
    print('\n')